package com.lucas.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.lucas.exception.MyException;
import com.lucas.service.TokenService;
import com.lucas.service.UserService;
import com.lucas.utils.CookiesUtil;
import com.lucas.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.net.http.HttpHeaders;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: spring_cloud_lagou_homework
 * @author: lucasLu
 **/
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private TokenService tokenService;

    /**
     * 注册方法
     * @param email
     * @param password
     * @param code
     * @return
     */
    @RequestMapping("/register/{email}/{password}/{code}")
    public Result  register(@PathVariable String email , @PathVariable String password, @PathVariable String code, HttpServletResponse response){
        System.out.println("userController 接受到参数 email :"+email+", password:"+password+", code:"+code);
        try {
            boolean registerOk = userService.register(email, password, code);
            if(!registerOk){
                return Result.error(100,"注册失败");
            }
        }catch (MyException e){
            return Result.error(100, e.getMsg()).put("data", false);
        }

        //注册成功的话,获取token
        String token = tokenService.getOrCreatToken(email);
        CookiesUtil.addCookies("USER_TOKEN",token,response);

        return Result.ok().put("data",0);
    }

    @RequestMapping("/isRegistered/{email}")
    public Result isRegistered(@PathVariable String email){
        return Result.ok().put("data",userService.isRegistered(email));
    }

    @RequestMapping("/login/{email}/{password}")
    public Result login(@PathVariable String email , @PathVariable  String password, HttpServletResponse reponse){
        boolean login = userService.login(email, password);
        if(!login){
            return Result.error(100,"登录失败");
        }
        String token = tokenService.getOrCreatToken(email);
        CookiesUtil.addCookies("USER_TOKEN",token,reponse);
        return Result.ok().put("data",email);
    }

    @RequestMapping("/logout")
    public Result logout(HttpServletResponse response){
        CookiesUtil.removeCookie("USER_TOKEN",response);
        return Result.ok();
    }

    @RequestMapping("/info")
    public Result info(@CookieValue(value = "USER_TOKEN",required = false)String token){
        String emailByToken = tokenService.getEmailByToken(token);
        if(StringUtils.isBlank(emailByToken)){
            return Result.error(100,"查询不到email");
        }
        return Result.ok().put("data",emailByToken);
    }
}
